package com.wd.tw.service;

import com.wd.tw.config.AppConfig;
import com.wd.tw.domain.entity.ElevatorInfo;
import com.wd.tw.domain.entity.ElevatorRunRecord;
import com.wd.tw.domain.entity.ElevatorRunTime;
import com.wd.tw.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.INTERNAL;
import org.springframework.stereotype.Service;
import sun.rmi.server.InactiveGroupException;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @className: BooleanCountService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/21
 **/

@Service
@Slf4j
public class BooleanCountService {

    @Resource
    AppConfig appConfig;

    @Resource
    ModbusService modbusService;

    @Resource
    ElevatorConfigService elevatorConfigService;

    @Resource
    ElevatorRunRecordService runRecordService;

    @Resource
    ElevatorRunTimeService runTimeService;

    private Map<Integer, Boolean> preStateMap = new HashMap<>();

    private Map<Integer, Integer> countMap = new HashMap<>();

    private Map<Integer, Long> runTimeMap = new HashMap<>();

    public void countChanges(Map<Integer, Boolean> curState) {
        for (Integer key : curState.keySet()) {
            Boolean state = curState.get(key);

            if (state == true) {
                if (runTimeMap.get(key) == null) {
                    runTimeMap.put(key, TimeUtils.getCurrentTime());
                }
                Boolean preState = preStateMap.get(key);
                if (preState == null || preState == false) {
                    Integer ct = countMap.get(key);
                    if (ct == null) {
                        ct = 0;
                    }
                    ct += 1;
                    countMap.put(key, ct);
                }
            }
            preStateMap.put(key, state);
        }

    }

    public Map<Integer, Boolean> getPreStateMap() {
        return preStateMap;
    }

    public Map<Integer, Integer> getCountMap() {
        return countMap;
    }

    public Map<Integer, Long> getRunTimeMap() {
        return runTimeMap;
    }


    /**
     * 运行时长
     *
     * @param channel
     * @return
     */
//    public int getRunTimeByChannel(int channel) {
//        List<Integer> signalList = getSignalList(channel);
//        Long sTime = TimeUtils.getCurrentTime();
//        for (int i = 0; i < signalList.size(); i++) {
//            Long aLong = runTimeMap.get(signalList.get(i));
//            if (aLong != null && aLong < sTime) {
//                sTime = aLong;
//            }
//        }
//        long differenceInSeconds = TimeUtils.getCurrentTime() - sTime;
//
//        // 将秒数转换为分钟数，向下取整
//        return (int) differenceInSeconds / 60;
//    }

    /**
     * 运行时长
     * @return
     */
    public Map<Long, Long> getEleRunTime() {
        Map<Long, Long> curRunTimeMap = new HashMap<>();
        List<ElevatorInfo> elevatorInfoList = elevatorConfigService.getElevatorInfoList();
        // 使用 map 和 reduce 实现分组
        Map<Long, List<ElevatorInfo>> groupingMap = elevatorInfoList.stream().collect(Collectors.groupingBy(ElevatorInfo::getElevatorId));
        for (Long key : groupingMap.keySet()) {
            List<ElevatorInfo> elevatorInfos = groupingMap.get(key);
            Long sTime = TimeUtils.getCurrentTime();
            if (elevatorInfos != null && elevatorInfoList.size() > 0) {

                for (int i = 0; i <elevatorInfos.size() ; i++) {
                    Long aLong = runTimeMap.get(elevatorInfos.get(i).getSignalId().intValue());
                    if (aLong != null && aLong < sTime) {
                        sTime = aLong;
                    }
                }
                curRunTimeMap.put(key,sTime);
            }
        }
        return curRunTimeMap;
    }


    public void resetState() {
        preStateMap = new HashMap<>();
        countMap = new HashMap<>();
        runTimeMap = new HashMap<>();
    }

    //通过modbus读取电梯状态
    public void countState() {
        boolean[] booleans = modbusService.readState(appConfig.getOffset(), appConfig.getNum());
        Map<Integer, Boolean> curState = new HashMap<>();
        List<Integer> elevatorSignal = elevatorConfigService.getElevatorSignal();
        for (int i = 0; i < elevatorSignal.size(); i++) {
            curState.put(elevatorSignal.get(i), booleans[elevatorSignal.get(i)]);
        }
        countChanges(curState);
//        Map<Integer, Boolean> curState = new HashMap<>();
//        List<Integer> elevatorSignal = elevatorConfigService.getElevatorSignal();
//        for (int i = 0; i < elevatorSignal.size(); i++) {
//            Random random = new Random();
//            boolean b = random.nextBoolean();
//            curState.put(elevatorSignal.get(i),b);
//        }
//        countChanges(curState);

    }

    //获取电梯运行的次数
    public Map<Long, Integer> getElevatorState() {
        List<ElevatorInfo> elevatorInfoList = elevatorConfigService.getElevatorInfoList();
        Map<Long, Integer> stateMap = new HashMap<>();
        for (int i = 0; i < elevatorInfoList.size(); i++) {
            ElevatorInfo elevatorInfo = elevatorInfoList.get(i);
            //运行次数
            Integer runCount = countMap.get(elevatorInfo.getSignalId().intValue());
            Long elevatorId = elevatorInfo.getElevatorId();
            //一个电梯可能对应的是多个
            if (stateMap.get(elevatorId) == null) {
                stateMap.put(elevatorId, runCount);
            } else {
                stateMap.put(elevatorId, stateMap.get(elevatorId) + countMap.get(elevatorInfo.getSignalId().intValue()));
            }
        }
        return stateMap;
    }

    public void writeState() {
        //运行次数
        Map<Long, Integer> elevatorState = getElevatorState();
        for (Long key : elevatorState.keySet()) {
            ElevatorRunRecord elevatorRunRecord = new ElevatorRunRecord();
            elevatorRunRecord.setElevatorId(key);
            elevatorRunRecord.setRunTimes(elevatorState.get(key).longValue());
            elevatorRunRecord.setRecordDate(TimeUtils.getCurrentDate());
            runRecordService.insertElevatorRunRecord(elevatorRunRecord);
        }

        //运行时间
        Map<Long, Long> eleRunTime = getEleRunTime();
        for (Long key : eleRunTime.keySet()) {
            ElevatorRunTime elevatorRunTime = new ElevatorRunTime();
            elevatorRunTime.setElevatorId(key);
            elevatorRunTime.setStartTime(eleRunTime.get(key));
            elevatorRunTime.setRecordDate(TimeUtils.getCurrentDate());
            runTimeService.insertElevatorRunTime(elevatorRunTime);
        }
    }

}
